#!/usr/bin/evn python
# examples/proxyserv_v1.py

try:
    import httpmessage
except ImportError:
    import sys
    from os.path import dirname, abspath, join
    sys.path.append(abspath(join(dirname(__file__), '..')))

from SocketServer import TCPServer, StreamRequestHandler, ThreadingMixIn
from httpmessage import HttpMessage

class ThreadingProxyServer(ThreadingMixIn, TCPServer):
    allow_reuse_address = True
    daemon_threads = True

class ProxyHandler(StreamRequestHandler):

    """Buffers the entire request before sending it to server. Buffers entire
    response before sending it to client. Doesn't work at all well for large
    resources (like Youtube videos)."""

    def handle(self):
        request = HttpMessage(socket=self.connection)
        response = request.fetch_response()
        response.connection = 'close'
        self.connection.send(str(response))


if __name__ == "__main__":
    server_address = ('', 8000)
    proxyserver = ThreadingProxyServer(server_address, ProxyHandler)
    print 'proxy serving on %r' % (server_address,)
    try:
        proxyserver.serve_forever()
    except KeyboardInterrupt:
        print '\nexiting...'

